import getUserTempId from "@/utils/userTempId"
import { reqLogin, reqGetUserInfo, reqLogOut } from "@/api"
import { getLocalToken, setLocalToken, removeLocalToken } from "@/utils/token"
const state = {
    userTempId: getUserTempId(),
    token: getLocalToken() || '',
    userInfo: {}


}
const mutations = {
    setToken(state, payload) {
        state.token = payload.token
        setLocalToken(payload.token)
    },
    setUserInfo(state, payload) {
        state.userInfo = payload.userInfo
    },
    resetUserInfo(state) {
        state.token = "",
            state.userInfo = {},
            removeLocalToken()
    }
}
const actions = {
    async getToken({ commit }, payload) {

        try {
            const re = await reqLogin(payload)
            commit('setToken', { token: re.token })
        } catch (e) {
            return Promise.reject(e)
        }
    },
    async getUserInfo({ commit }) {

        try {
            const re = await reqGetUserInfo()
            // console.log(re);
            commit('setUserInfo', { userInfo: re })
        } catch (e) {
            return Promise.reject(e)
        }
    },
    async logOut({ commit }) {
        try {
            await reqLogOut();
            commit('resetUserInfo')
        } catch (e) { return Promise.reject(e) }
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}